﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Composition;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Core;
using CC98.ComponentModel;

namespace CC98.Metro.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Splash : Page
    {
        public Splash()
        {
            this.InitializeComponent();
            this._initProcessor = App.Current.CompositionHost.GetExport<InitializeProcessor>();
            this._initProcessor.ProgressChanged += InitProcessor_ProgressChanged;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this._splashScreen = (SplashScreen)e.Parameter;
            this._splashScreen.Dismissed += SplashScreenDismissed;
            this.RearrangeLogo(this._splashScreen.ImageLocation);
        }

        private void SplashScreenDismissed(SplashScreen sender, object args)
        {
            // Complete
            this._splashScreen.Dismissed -= SplashScreenDismissed;
            // Start to load application data
            this._initProcessor.StartAsync(ActionScope.App, new Action<System.Threading.Tasks.Task>((task) =>
                {
                    if (task.Exception != null)
                    {
                        // Failed to initialize
                    }
                    else
                    {
                        // Clear history in order to prevent from going back to this splash page
                        CommandHandler.Execute("ClearNavigationHistory", null);
                        // Naivgate to home page
                        CommandHandler.NavigateTo(typeof(Pages.Home), null);
                    }
                }));
        }

        private void RearrangeLogo(Rect rect)
        {
            this.logo.SetValue(Canvas.LeftProperty, rect.X);
            this.logo.SetValue(Canvas.TopProperty, rect.Y);
            this.logo.Height = rect.Height;
            this.logo.Width = rect.Width;
        }

        void InitProcessor_ProgressChanged(object sender, InitializeProcessorProgressChangedEventArgs e)
        {
            this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
                {
                    this.stage.Content = e.Name;
                }));
        }

        private SplashScreen _splashScreen;

        private InitializeProcessor _initProcessor;
    }
}
